using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
using System.Text;

public partial class Pages_Invoice : System.Web.UI.Page
{
    
    public static int addornegate = 1; // used to +/- of the saved item's quantity in ton/pcs
    public static int Party_acctype = 0;
    public static int Party_acccode = 0;
    public static string Party_accname = string.Empty;
    public static string Party_acctypename = string.Empty;
    private const string DATE_INFO = "date";
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {

            //Call the DateCokkie function so that it can get the date info from cookie
            //as soon as the page gets loded
            GetDateCookie();

            TextBoxDate.Text = DateTime.Today.ToString();
            DropDownList1.SelectedIndex = 0;
            DropDownList1_SelectedIndexChanged(null, null);

            Button_Delivery.Enabled = false;
            Button_Party_Select.Enabled = false;


            PopulateGrid();
            Button_PutItem.Enabled = false;
        }

    }

    private void PopulateGrid()
    {
        Button_PutItem.Enabled = false;

        txtAccCodeValue.Text = string.Empty;
        txtAccTypeName.Text = string.Empty;
        txtAccCodeName.Text = string.Empty;
        txtAccTypeValue.Text = string.Empty;
        
        
        #region populate and bind itemlist with grid
        DataSet ds = new DataSet();
        //Common.Getdata(ds, "select ITYPE,ICODE,INAME,PRICE from stock", "Stk");


        //Common.Getdata(ds, "select DESCRIPT,CODE from TYPE WHERE VARFIELD='ITYPE' and TYPE='FI' and CODE>0", "type");


        DataTable dtMemoBuffer = new DataTable();
        dtMemoBuffer.TableName = "dtMemoBuffer";
        dtMemoBuffer.Columns.Add("icode", typeof(int));
        dtMemoBuffer.Columns.Add("ton", typeof(decimal));
        dtMemoBuffer.Columns.Add("cost", typeof(decimal));
        dtMemoBuffer.Columns.Add("itype", typeof(int));
        dtMemoBuffer.Columns.Add("descript", typeof(string));
        dtMemoBuffer.Columns.Add("itypestring", typeof(string));
        dtMemoBuffer.Columns.Add("inamestring", typeof(string));
        dtMemoBuffer.Columns.Add("rowtotal", typeof(decimal));
        dtMemoBuffer.Columns.Add("pcs", typeof(decimal));



         GridView3.DataSource = dtMemoBuffer;
        GridView3.DataBind();
        #endregion

        #region create data table for account input and bind it with grid

        DataTable dtCreditAccBuffer = new DataTable();
        dtCreditAccBuffer.TableName = "dtCreditAccBuffer";
        dtCreditAccBuffer.Columns.Add("date", typeof(DateTime));
        dtCreditAccBuffer.Columns.Add("nature", typeof(string));
        dtCreditAccBuffer.Columns.Add("refn", typeof(float));
        dtCreditAccBuffer.Columns.Add("acccode", typeof(int));
        dtCreditAccBuffer.Columns.Add("acctype", typeof(int));
        dtCreditAccBuffer.Columns.Add("accname", typeof(string));
        dtCreditAccBuffer.Columns.Add("acctypename", typeof(string));
        dtCreditAccBuffer.Columns.Add("amount", typeof(decimal));
        dtCreditAccBuffer.Columns.Add("debexp", typeof(string));
 //       dtCreditAccBuffer.Columns.Add("explain", typeof(string));

        DataTable dtDebitAccBuffer = new DataTable();
        dtDebitAccBuffer.TableName = "dtDebitAccBuffer";
        dtDebitAccBuffer.Columns.Add("date", typeof(DateTime));
        dtDebitAccBuffer.Columns.Add("nature", typeof(string));
        dtDebitAccBuffer.Columns.Add("refn", typeof(float));
        dtDebitAccBuffer.Columns.Add("acccode", typeof(int));
        dtDebitAccBuffer.Columns.Add("acctype", typeof(int));
        dtDebitAccBuffer.Columns.Add("accname", typeof(string));
        dtDebitAccBuffer.Columns.Add("acctypename", typeof(string));
        dtDebitAccBuffer.Columns.Add("amount", typeof(decimal));
        dtDebitAccBuffer.Columns.Add("debexp", typeof(string));
   //     dtDebitAccBuffer.Columns.Add("explain", typeof(string));

        GridView1.DataSource = dtDebitAccBuffer;
        GridView1.DataBind();


        GridView2.DataSource = dtCreditAccBuffer;
        GridView2.DataBind();



        #endregion

        if (Session["Finished Good Entry"] != null)
        {
            Session.Remove("Finished Good Entry");
        }
        Session.Add("Finished Good Entry", dtMemoBuffer);

        if (Session["Account Credit Entry"] != null)
        {
            Session.Remove("Account Credit Entry");
        }
        Session.Add("Account Credit Entry", dtCreditAccBuffer);

        if (Session["Account Debit Entry"] != null)
        {
            Session.Remove("Account Debit Entry");
        }
        Session.Add("Account Debit Entry", dtDebitAccBuffer);

    }
    protected void GridView3_SelectedIndexChanged(object sender, EventArgs e)
    {

        DataTable dtMemoBuffer = new DataTable();
        dtMemoBuffer = (DataTable)Session["Finished Good Entry"];
        if (GridView3.SelectedIndex > -1)
        {
            int i = GridView3.SelectedIndex;
            decimal cost = Convert.ToDecimal(dtMemoBuffer.Rows[i]["cost"]);
            decimal ton = Convert.ToDecimal(dtMemoBuffer.Rows[i]["ton"]);
            TextBoxton.Text = ton.ToString();
            TextBoxAmount.Text = cost.ToString();

            //txtAccCodeValue.Text = Convert.ToString(dtMemoBuffer.Rows[i]["acccode"]);
            //txtAccTypeName.Text = Convert.ToString(dtMemoBuffer.Rows[i]["acctypename"]);
            //txtAccCodeName.Text = Convert.ToString(dtMemoBuffer.Rows[i]["accname"]);
            //txtAccTypeValue.Text = Convert.ToString(dtMemoBuffer.Rows[i]["acctype"]);
        }

    }
    protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        GridView1.DataSource = null;
        GridView1.DataBind();
        GridView3.DataSource = null;
        PopulateGrid();
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
       

        


        if (DropDownList1.SelectedValue.ToString() == "FRM")
        {
            BtnStkAccount.Enabled = false;
            BtnStkAccount.Text = " ";
            btnUpdateAcc.Enabled = false;
            btnUpdateAcc.Text = " ";
            TextBoxRefNature.Text = "FRM " + Common.GetRefn("FRM", Convert.ToDateTime(TextBoxDate.Text.ToString()).Year.ToString()).ToString();
            addornegate = 1;  // used to +/- of the saved item's quantity in ton/pcs
            Button_PutItem.Enabled = true;
        }

        if (DropDownList1.SelectedValue.ToString() == "IV")
        {
            BtnStkAccount.Enabled = true;
            BtnStkAccount.Text = "Select Client / Debit";
            btnUpdateAcc.Enabled = true;
            btnUpdateAcc.Text = "Select Credit";
            TextBoxRefNature.Text = "IV " + Common.GetRefn("IV", Convert.ToDateTime(TextBoxDate.Text.ToString()).Year.ToString()).ToString();
            addornegate = -1;
            Button_PutItem.Enabled = true;
            Button_Party_Select.Enabled = true;
        }



        GridView1.DataSource = null;
        GridView1.DataBind();
        GridView3.DataSource = null;
        PopulateGrid();
    }
    protected void ButtonDebit_Click(object sender, EventArgs e)
    {
        
        try
        {
            if (!(Common.IsRightDecimalEntry(TextBox_accamount.Text)))
            {
                Label1.Text = "Incorrect decimal entry";
                return;
            }

            Label1.Text = " ";
            
            DataTable  dtDebitAccBuffer = new DataTable();
            dtDebitAccBuffer = (DataTable)Session["Account Debit Entry"];

            #region If the account already exists in table do not add a new one again
            int k;


            for (k = 0; k < dtDebitAccBuffer.Rows.Count; k++)  // find if the "sales of cisheet" account already exists
            {
                if (Convert.ToInt32(dtDebitAccBuffer.Rows[k]["acctype"]) == Common.accTypeValue)
                    if (Convert.ToInt32(dtDebitAccBuffer.Rows[k]["acccode"]) == Common.accCodeValue)
                        return;
            }

            #endregion




            DataRow dr = dtDebitAccBuffer.NewRow();
            dr["acccode"] = Common.accCodeValue;
            dr["acctypename"] = Common.accTypeName;
            dr["accname"] = Common.accCodeName;
            dr["acctype"] = Common.accTypeValue;
            dr["amount"] = TextBox_accamount.Text;



            dtDebitAccBuffer.Rows.Add(dr);

            GridView1.DataSource = null;
            GridView1.DataSource = dtDebitAccBuffer;
            GridView1.DataBind();
            // GridView2.SelectedIndex = -1;


            if (Session["Account Debit Entry"] != null)
            {
                Session.Remove("Account Debit Entry");
            }
            Session.Add("Account Debit Entry", dtDebitAccBuffer);
        }
        catch (Exception Ex)
        {

            Label1.Text = Ex.Message;
        }

    }
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    protected void BtnUpdateAcc_Click(object sender, EventArgs e)
    {
        try
        {

            Label1.Text = " ";

            if (!Common.IsRightDecimalEntry(TextBox_accamount.Text))
            {
                Label1.Text = "decimal format not ok";
                return;
            }
            

            DataTable dtCreditAccBuffer = new DataTable();
            dtCreditAccBuffer = (DataTable)Session["Account Credit Entry"];

            #region If the account already exists in table do not add a new one again
            int k;
            int found=0;

            for (k = 0; k < dtCreditAccBuffer.Rows.Count; k++)  // find if the "sales of cisheet" account already exists
            {
                if (Convert.ToInt32(dtCreditAccBuffer.Rows[k]["acctype"]) == Common.accTypeValue)
                    if (Convert.ToInt32(dtCreditAccBuffer.Rows[k]["acccode"]) == Common.accCodeValue)
                    {
                        dtCreditAccBuffer.Rows[k]["amount"] = Convert.ToDecimal(TextBox_accamount.Text);
                        found = 1;
                    }
                        
            }
            
            #endregion
            
            if (found == 0)
            {
                DataRow dr = dtCreditAccBuffer.NewRow();
                dr["acccode"] = Common.accCodeValue;
                dr["acctypename"] = Common.accTypeName;
                dr["accname"] = Common.accCodeName;
                dr["acctype"] = Common.accTypeValue;
                dr["amount"] = Convert.ToDecimal(TextBox_accamount.Text); 

                dtCreditAccBuffer.Rows.Add(dr);
            }

            GridView2.DataSource = null;
            GridView2.DataSource = dtCreditAccBuffer;
            GridView2.DataBind();
            GridView2.SelectedIndex = -1;


            if (Session["Account Credit Entry"] != null)
            {
                Session.Remove("Account Credit Entry");
            }
            Session.Add("Account Credit Entry", dtCreditAccBuffer);
        }
        catch (Exception Ex)
        {

            Label1.Text = Ex.Message;
        }
    }

    protected void GridView3_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

        if (GridView3.SelectedIndex > -1)
        {
            DataTable dtMemoBuffer = new DataTable();
            dtMemoBuffer = (DataTable)Session["Finished Good Entry"];


            int i = GridView3.SelectedIndex;

            dtMemoBuffer.Rows.RemoveAt(i);
            dtMemoBuffer.AcceptChanges();
            
            GridView3.DataSource = null;
            GridView3.DataSource = dtMemoBuffer;
            GridView3.DataBind();
            
            GridView3.SelectedIndex = -1;

            



            if (Session["Finished Good Entry"] != null)
            {
                Session.Remove("Finished Good Entry");
            }
            Session.Add("Finished Good Entry", dtMemoBuffer);
        }
    }

    protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            if (GridView2.SelectedIndex > -1)
            {
                DataTable dtCreditAccBuffer = new DataTable();
                dtCreditAccBuffer = (DataTable)Session["Account Credit Entry"];

                dtCreditAccBuffer.Rows.RemoveAt(GridView2.SelectedIndex);
                dtCreditAccBuffer.AcceptChanges();

                GridView2.DataSource = null;
                GridView2.DataSource = dtCreditAccBuffer;
                GridView2.DataBind();
                GridView2.SelectedIndex = -1;



                if (Session["Account Credit Entry"] != null)
                {
                    Session.Remove("Account Credit Entry");
                }
                Session.Add("Account Credit Entry", dtCreditAccBuffer);
            }
        }
        catch (Exception Ex)
        {
            Label1.Text = Ex.Message;
            throw;
        }
    }
    
    protected void BtnSave_Click(object sender, EventArgs e)
    {
        






    }


    protected void Button_account_amount_Click(object sender, EventArgs e)
    {
        try
        {

            if ((GridView2.SelectedIndex > -1) && (GridView1.SelectedIndex > -1))
            {
                GridView1.SelectedIndex=-1;
                GridView2.SelectedIndex=-1;
                return;
            }


            if (!(Common.IsRightDecimalEntry(TextBox_accamount.Text)))
            {
                Label1.Text="Incorrect Decimal entry";
                return;
            }

            decimal amount = Convert.ToDecimal(TextBox_accamount.Text);

            
                        
            if (GridView2.SelectedIndex > -1)
            {
                DataTable dtCreditAccBuffer = new DataTable();
                dtCreditAccBuffer = (DataTable)Session["Account Credit Entry"];

                int i = GridView2.SelectedIndex;
                dtCreditAccBuffer.Rows[i]["amount"] = amount;
                GridView2.DataSource = null;
                GridView2.DataSource = dtCreditAccBuffer;
                GridView2.DataBind();
                GridView2.SelectedIndex = -1;

                if (Session["Account Credit Entry"] != null)
                {
                    Session.Remove("Account Credit Entry");
                }
                Session.Add("Account Credit Entry", dtCreditAccBuffer);


            }
            if (GridView1.SelectedIndex > -1)
            {
                DataTable dtDebitAccBuffer = new DataTable();
                dtDebitAccBuffer = (DataTable)Session["Account Debit Entry"];

                int i = GridView1.SelectedIndex;
                dtDebitAccBuffer.Rows[i]["amount"] = amount;
                GridView1.DataSource = null;
                GridView1.DataSource = dtDebitAccBuffer;
                GridView1.DataBind();
                GridView1.SelectedIndex = -1;

                if (Session["Account Debit Entry"] != null)
                {
                    Session.Remove("Account Debit Entry");
                }
                Session.Add("Account Debit Entry", dtDebitAccBuffer);
            }
            
        }
        catch (Exception Ex)
        {

            Label1.Text = Ex.Message;
        }
    }
 
    protected void TextBoxton_Load(object sender, EventArgs e)
    {
        //TextBoxton_TextChanged(null, null);
        TextBoxAmount.Text = Common.stkPrice.ToString();
    }
    protected void Button_PutItem_Click(object sender, EventArgs e)
    {

        Boolean tongiven=false;
        Label1.Text="";
        // check whether all entries are ok
        if (string.IsNullOrEmpty(Common.stkCodeName)) {Label1.Text="error 754"; return;}
        if (Common.stkCodeValue<1) {Label1.Text="error 756"; return;}
        if (!(string.IsNullOrEmpty(TextBoxton.Text)))
        {
                tongiven = true;
                if (!Common.IsRightDecimalEntry(TextBoxton.Text)) { Label1.Text = "error 760"; return; }; 
        }
        else
        {
                tongiven = false; 
                if (!Common.IsRightIntegerEntry(TextBoxPcs.Text)) {Label1.Text="error 765"; return;}; 
        }
        if (!string.IsNullOrEmpty(TextBoxAmountNew.Text))
            if (!Common.IsRightDecimalEntry(TextBoxAmountNew.Text)) { Label1.Text = "error 768"; return; };

        #region Update dtMemoBuffer with items

        DataTable dtMemoBuffer = new DataTable();
        dtMemoBuffer = (DataTable)Session["Finished Good Entry"];

        //find if the selected entry is already in the table, if it is there update the price
        int k;
        int found = 0;
        decimal qty;

        for (k = 0; k < dtMemoBuffer.Rows.Count; k++)  // find if the selected item already exists
        {
            if (Convert.ToInt32(dtMemoBuffer.Rows[k]["itype"]) == Common.stkTypeValue)
                if (Convert.ToInt32(dtMemoBuffer.Rows[k]["icode"]) == Common.stkCodeValue)
                {
                    if (tongiven)
                    {
                        dtMemoBuffer.Rows[k]["ton"] = Convert.ToDecimal(TextBoxton.Text);
                        dtMemoBuffer.Rows[k]["pcs"] = 0;
                        qty = Convert.ToDecimal(TextBoxton.Text);
                    }
                    else
                    {
                        dtMemoBuffer.Rows[k]["ton"] = 0;
                        dtMemoBuffer.Rows[k]["pcs"] = Convert.ToDecimal(TextBoxPcs.Text);
                        qty = Convert.ToDecimal(TextBoxPcs.Text);
                    }
                    if (string.IsNullOrEmpty(TextBoxAmountNew.Text))
                    {
                        // dtMemoBuffer.Rows[k]["cost"] = Convert.ToDecimal(TextBoxAmount.Text);
                        dtMemoBuffer.Rows[k]["rowtotal"] = qty * Convert.ToDecimal(dtMemoBuffer.Rows[k]["cost"].ToString());
                    }
                    else
                    {
                        dtMemoBuffer.Rows[k]["cost"] = Convert.ToDecimal(TextBoxAmountNew.Text);
                        dtMemoBuffer.Rows[k]["rowtotal"] = qty * Convert.ToDecimal(TextBoxAmountNew.Text);
                    }
                    found = 1;
                }
        }

        if (found == 0)
        {


            TextBoxAmount.Text = Common.GetItemPrice(Common.stkTypeValue, Common.stkCodeValue).ToString();
            if (tongiven)
                dtMemoBuffer.Rows.Add(Common.stkCodeValue, Convert.ToDecimal(TextBoxton.Text), Convert.ToDecimal(TextBoxAmount.Text), Common.stkTypeValue, "", Common.stkTypeName, Common.stkCodeName, Convert.ToDecimal(TextBoxton.Text) * Convert.ToDecimal(TextBoxAmount.Text), 0);
            else
                dtMemoBuffer.Rows.Add(Common.stkCodeValue, 0, Convert.ToDecimal(TextBoxAmount.Text), Common.stkTypeValue, "", Common.stkTypeName, Common.stkCodeName, Convert.ToInt32(TextBoxPcs.Text) * Convert.ToDecimal(TextBoxAmount.Text), Convert.ToInt32(TextBoxPcs.Text));
        } 
        #endregion

    #region Find the total cost of CISheet,Ridge and update account of Sales of CISheet and party account respectively

    DataTable dtCreditAccBuffer = new DataTable();
    dtCreditAccBuffer = (DataTable)Session["Account Credit Entry"];
    DataTable dtDebitAccBuffer = new DataTable();
    dtDebitAccBuffer = (DataTable)Session["Account Debit Entry"];
    DataTable dtBriefMemoBuffer = dtMemoBuffer.Clone();

    string filterExp = "ton > 0 or pcs > 0";
    DataRow[] drarray;
    drarray = dtMemoBuffer.Select(filterExp);
    decimal ridge_price_total = 0;
    decimal cisheet_price_total = 0;
    foreach (DataRow row in drarray)
    {
        //dtBriefMemoBuffer.ImportRow(row);
        if (Convert.ToInt32(row["itype"]) != 14) // the item is not a RIDGE type item
            cisheet_price_total = cisheet_price_total + Convert.ToDecimal(row["rowtotal"]);
        else
            ridge_price_total = ridge_price_total + Convert.ToDecimal(row["rowtotal"]);
    }

    // Update GridView1,2 with sales accounts of CISheet, Sales of Ridge

    int j;
    int foundacc = 0;

    for (j = 0; j < dtCreditAccBuffer.Rows.Count; j++)  // find if the "sales of cisheet" account already exists
    {
        if (Convert.ToInt32(dtCreditAccBuffer.Rows[j]["acctype"]) == 78)
            if (Convert.ToInt32(dtCreditAccBuffer.Rows[j]["acccode"]) == 1)
            {
                dtCreditAccBuffer.Rows[j]["amount"] = cisheet_price_total + ridge_price_total;
                foundacc = 1;
            }
    }
    for (j = 0; j < dtDebitAccBuffer.Rows.Count; j++)  // find if the party account already exists
    {
        if (Convert.ToInt32(dtDebitAccBuffer.Rows[j]["acctype"]) == Party_acctype)
            if (Convert.ToInt32(dtDebitAccBuffer.Rows[j]["acccode"]) == Party_acccode)
                if (dtDebitAccBuffer.Rows[j]["debexp"] != "Delivery Charge")
                {
                dtDebitAccBuffer.Rows[j]["amount"] = cisheet_price_total + ridge_price_total;
                foundacc = 1;
                }
    }
    if (foundacc == 0)
    {
        dtCreditAccBuffer.Rows.Add("01/01/2001", "", 0, 1, 78, "C.I.Sheet", "Sales of C.I.Sheet", cisheet_price_total + ridge_price_total, "To " + Party_accname);
        dtDebitAccBuffer.Rows.Add("01/01/2001", "", 0, Party_acccode, Party_acctype, Party_acctypename, Party_accname, cisheet_price_total + ridge_price_total, "To Sales of C.I.Sheet");
    }

    GridView1.DataSource = null;
    GridView1.DataSource = dtDebitAccBuffer;
    GridView1.DataBind();


    GridView2.DataSource = null;
    GridView2.DataSource = dtCreditAccBuffer;
    GridView2.DataBind();

    #endregion

        
        GridView3.DataSource = null;
        GridView3.DataSource = dtMemoBuffer;
        GridView3.DataBind();

        if (Session["Account Credit Entry"] != null)
        {
            Session.Remove("Account Credit Entry");
        }
        Session.Add("Account Credit Entry", dtCreditAccBuffer);

        if (Session["Account Debit Entry"] != null)
        {
            Session.Remove("Account Debit Entry");
        }
        Session.Add("Account Debit Entry", dtDebitAccBuffer);

        if (Session["Finished Good Entry"] != null)
        {
            Session.Remove("Finished Good Entry");
        }
        Session.Add("Finished Good Entry", dtMemoBuffer);




    }
    protected void GridView1_SelectedIndexChanged1(object sender, EventArgs e)
    {

    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            if (GridView1.SelectedIndex > -1)
            {
                DataTable dtDebitAccBuffer = new DataTable();
                dtDebitAccBuffer = (DataTable)Session["Account Debit Entry"];

                dtDebitAccBuffer.Rows.RemoveAt(GridView1.SelectedIndex);
                dtDebitAccBuffer.AcceptChanges();

                GridView1.DataSource = null;
                GridView1.DataSource = dtDebitAccBuffer;
                GridView1.DataBind();
                GridView1.SelectedIndex = -1;



                if (Session["Account Debit Entry"] != null)
                {
                    Session.Remove("Account Debit Entry");
                }
                Session.Add("Account Debit Entry", dtDebitAccBuffer);
            }
        }
        catch (Exception Ex)
        {
            Label1.Text = Ex.Message;
            throw;
        }
    }
    protected void BtnSave_Click1(object sender, EventArgs e)
    {
        try
        {
            //set the date cookie first
            HttpCookie _cookie = new HttpCookie(DATE_INFO);
            _cookie[DATE_INFO] = TextBoxDate.Text;
            _cookie.Expires = DateTime.Now.AddDays(1);
            Response.Cookies.Add(_cookie);

            Label1.Text = "";
            
            #region  check whether new entry is possible, logic is,
            // if the balance sheet is saved for this month, no entry is possible

            DataSet ds = new DataSet();
            //Common.Getdata(ds, "select OK from defbshit where year_code=" + DropDownListYear.SelectedValue + " and month_type=" + DropDownListMonth.SelectedValue, "okvalue");
            string query = "select OK from defbshit where year_code=" + Convert.ToDateTime(TextBoxDate.Text.ToString()).Year.ToString() + " and month_type=" + Convert.ToDateTime(TextBoxDate.Text.ToString()).Month.ToString();
            Common.Getdata(ds, query, "okvalue");

            if (ds.Tables["okvalue"].Rows.Count < 1)
                Label1.Text = "Data cannot be saved in this future time";
            else if (!(ds.Tables["okvalue"].Rows[0][0] is DBNull))
                 if (Convert.ToInt32(ds.Tables["okvalue"].Rows[0][0]) == 1)
                    {
                        Label1.Text = "Data cannot be saved in this month,year of saved balanced sheet";
                        return;
                    }

            #endregion

            if (DropDownList1.SelectedValue.ToString()=="FRM")
            {
                Save_FRM();
                BtnSave.Enabled = false;
                return;
            }

            #region Count how many accounts are there and load them to dtAccBuffer, one check 
            // two checks to be done 1. check whether total debit =total credit
            
            DataTable dtCreditAccBuffer = new DataTable();
            DataTable dtDebitAccBuffer = new DataTable();
            dtCreditAccBuffer = (DataTable)Session["Account Credit Entry"];
            dtDebitAccBuffer = (DataTable)Session["Account Debit Entry"];
            int no_of_credit_accounts = dtCreditAccBuffer.Rows.Count;
            int no_of_Debit_accounts = dtDebitAccBuffer.Rows.Count;

            decimal total_debit = 0;
            foreach (DataRow accrow in dtCreditAccBuffer.Rows)
            {
                total_debit = total_debit + Convert.ToDecimal(accrow["amount"]);
            }
            decimal total_credit = 0;
            foreach (DataRow accrow in dtDebitAccBuffer.Rows)
            {
                total_credit = total_credit + Convert.ToDecimal(accrow["amount"]);
            }
            if (total_debit != total_credit)
            {
                Label1.Text = "Debit side is not equal to credit side";
                return;
            }
            #endregion

            #region Bring all the filled up entries of dtMemoBuffer into another table dtBriefMemoBuffer
            
            DataTable dtMemoBuffer = new DataTable();
            dtMemoBuffer = (DataTable)Session["Finished Good Entry"];

            DataTable dtBriefMemoBuffer = dtMemoBuffer.Clone();

            string filterExp = "ton > 0 or pcs > 0";
            DataRow[] drarray;
            drarray = dtMemoBuffer.Select(filterExp);

            foreach (DataRow row in drarray)
            {
                dtBriefMemoBuffer.ImportRow(row);
            }
            int no_of_items = dtBriefMemoBuffer.Rows.Count;
            #endregion

            #region Find the total cost of items from dtBriefMemoBuffer, another check
            // Of the two checks to be done 2. check total cost in dtMemoBuffer = total amount against sales of cisheet


            decimal total_cost_of_items = 0;
            decimal total_ton = 0;
            foreach (DataRow row in dtBriefMemoBuffer.Rows)
            {
                row["rowtotal"] = Convert.ToDecimal(row["ton"]) * Convert.ToDecimal(row["cost"]) + Convert.ToDecimal(row["pcs"]) * Convert.ToDecimal(row["cost"]);
                total_cost_of_items = total_cost_of_items + Convert.ToDecimal(row["rowtotal"]);
                total_ton = total_ton + Convert.ToDecimal(row["ton"]);
            }

            int j;
            // find if the "sales of cisheet" account has same figure as total cost of items
            for (j = 0; j < dtCreditAccBuffer.Rows.Count; j++) 
            {
                if (Convert.ToInt32(dtCreditAccBuffer.Rows[j]["acctype"]) == 78)
                    if (Convert.ToInt32(dtCreditAccBuffer.Rows[j]["acccode"]) == 1)
                    {
                        if (Convert.ToDecimal(dtCreditAccBuffer.Rows[j]["amount"]) !=total_cost_of_items)
                        {
                            Label1.Text = "Item total cost does not match to total amount posted at sales of CISHeet";
                            return;
                        }
                    }
            }
            #endregion


            #region connect to database and save each item in dtBriefMemoBuffer into MEMO table

            string conString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
            //string conString = @"Provider=SQLSql;Data Source=CSE-PC\SQLEXPRESS;User ID=sa;Initial Catalog=DB2011;Password=1234";
            SqlCommand myCommInsert = new SqlCommand();
            myCommInsert.Connection = new SqlConnection(conString);
            myCommInsert.Connection.Open();


            int refno;
            refno = Common.GetRefn(DropDownList1.SelectedValue.ToString(), Convert.ToDateTime(TextBoxDate.Text.ToString()).Year.ToString());
            string str_refno = Convert.ToString(refno);



            foreach (DataRow arow in dtBriefMemoBuffer.Rows)
            {

                // Save in Memo table
                string strQuery = "INSERT INTO [DB2011].[dbo].[MEMO]" +
                    " ([NATURE],[REFN],[DATE],[ITYPE], [ICODE],[W_TON], [COST],[QTY]) " +
                    "VALUES ('" + DropDownList1.SelectedValue.ToString() + "'," + refno + ",'" + TextBoxDate.Text.Trim() + "'" +
                    "," + arow["itype"] + "," + arow["icode"] + ",'" + addornegate * Convert.ToDouble(arow["ton"]) + "'," + Convert.ToDouble(arow["cost"]) + ",'" + addornegate * Convert.ToDouble(arow["pcs"]) + "')";
                myCommInsert.CommandText = strQuery;
                myCommInsert.ExecuteNonQuery();

            }

            foreach (DataRow accrow in dtCreditAccBuffer.Rows)
            {

                string strQuery2 = "INSERT INTO [DB2011].[dbo].[TRADE]" +
                    " ([NATURE],[REFN],[DATE],[TIME],[CRACCTYPE],[CREDITACC],[DEBACCTYPE],[DEBITACC],[AMOUNT],[TOTALTON],[debexp],[EXPLAIN])" +
                    " VALUES (" +
                    "'" + DropDownList1.SelectedValue.ToString() + "','" + refno +
                    "','" + TextBoxDate.Text.Trim() + "','" + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() +
                    "','" + accrow["acctype"] + "','" + accrow["acccode"] + "'," + "null" +
                    ",'" + (-1) * no_of_Debit_accounts + "','" + Convert.ToDouble(accrow["amount"]) +
                    "','" + Convert.ToDouble(total_ton) + "','" + accrow["debexp"].ToString() + 
                    "','" + TextBox_explain.Text.ToString() + "')";

                myCommInsert.CommandText = strQuery2;
                myCommInsert.ExecuteNonQuery();
            }

            foreach (DataRow accrow in dtDebitAccBuffer.Rows)
            {

                string strQuery3 = "INSERT INTO [DB2011].[dbo].[TRADE]" +
                    " ([NATURE],[REFN],[DATE],[TIME],[DEBACCTYPE],[DEBITACC],[CRACCTYPE],[CREDITACC],[AMOUNT],[TOTALTON],[debexp],[EXPLAIN])" +
                    " VALUES (" +
                    "'" + DropDownList1.SelectedValue.ToString() + "','" + refno +
                    "','" + TextBoxDate.Text.Trim() + "','" + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() +
                    "','" + accrow["acctype"] + "','" + accrow["acccode"] + "'," + "null" +
                    ",'" + (-1) * no_of_credit_accounts + "','" + Convert.ToDouble(accrow["amount"]) +
                    "','" + Convert.ToDouble(total_ton) + "','" + accrow["debexp"].ToString() +
                    "','" + TextBox_explain.Text.ToString() + "')";

                myCommInsert.CommandText = strQuery3;
                myCommInsert.ExecuteNonQuery();
            }
            myCommInsert.Connection.Close();
            Label1.Text = "saved successfully";
            BtnSave.Enabled = false;
            #endregion
        }
        catch (Exception Ex)
        {
            Label1.Text = Ex.Message;
            throw;
        }
    }

    protected void Save_FRM()
    {
        #region Bring all the filled up entries of dtMemoBuffer into another table dtBriefMemoBuffer

        DataTable dtMemoBuffer = new DataTable();
        dtMemoBuffer = (DataTable)Session["Finished Good Entry"];

        DataTable dtBriefMemoBuffer = dtMemoBuffer.Clone();

        string filterExp = "ton > 0 or pcs > 0";
        DataRow[] drarray;
        drarray = dtMemoBuffer.Select(filterExp);

        decimal total_cost = 0;
        decimal total_ton = 0;
        foreach (DataRow row in drarray)
        {
            dtBriefMemoBuffer.ImportRow(row);
            total_cost = total_cost + Convert.ToDecimal(row["rowtotal"]);
            total_ton = total_ton + Convert.ToDecimal(row["ton"]);
        }
        int no_of_items = dtBriefMemoBuffer.Rows.Count;
        #endregion

        #region connect to database and save each item in dtBriefMemoBuffer into MEMO table

        string conString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;

 //       string conString = @"Provider=SQLSql;Data Source=CSE-PC\SQLEXPRESS;User ID=sa;Initial Catalog=DB2011;Password=1234";
        SqlCommand myCommInsert = new SqlCommand();
        myCommInsert.Connection = new SqlConnection(conString);
        myCommInsert.Connection.Open();


        int refno;
        refno = Common.GetRefn(DropDownList1.SelectedValue.ToString(), Convert.ToDateTime(TextBoxDate.Text.ToString()).Year.ToString());
        string str_refno = Convert.ToString(refno);



        foreach (DataRow arow in dtBriefMemoBuffer.Rows)
        {

            // Save in Memo table
            string strQuery = "INSERT INTO [DB2011].[dbo].[MEMO]" +
                " ([NATURE],[REFN],[DATE],[ITYPE], [ICODE],[W_TON], [COST],[QTY]) " +
                "VALUES ('" + DropDownList1.SelectedValue.ToString() + "'," + refno + ",'" + TextBoxDate.Text.Trim() + "'" +
                "," + arow["itype"] + "," + arow["icode"] + ",'" + addornegate * Convert.ToDouble(arow["ton"]) + "'," + Convert.ToDouble(arow["cost"]) + ",'" + addornegate * Convert.ToDouble(arow["pcs"]) + "')";
            myCommInsert.CommandText = strQuery;
            myCommInsert.ExecuteNonQuery();

        }

        string strQuery3 = "INSERT INTO [DB2011].[dbo].[TRADE]" +
                " ([NATURE],[REFN],[DATE],[TIME],[AMOUNT],[TOTALTON])" +
                " VALUES (" +
                "'" + DropDownList1.SelectedValue.ToString() + "','" + refno +
                "','" + TextBoxDate.Text.Trim() + "','" + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() +
                "','" + Convert.ToDouble(total_cost) + "','" + Convert.ToDouble(total_ton) + "')";
        myCommInsert.CommandText = strQuery3;
        myCommInsert.ExecuteNonQuery();
        
        myCommInsert.Connection.Close();
        Label1.Text = "saved successfully";
        #endregion



    }
    protected void DropDownListYear_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList1_SelectedIndexChanged(null, null);
       
    }
    protected void DropDownListMonth_SelectedIndexChanged(object sender, EventArgs e)
    {
        Button_PutItem.Enabled = true;
    }
    protected void Button_Party_Select_Click(object sender, EventArgs e)
    {
        Party_acctype = Common.accTypeValue;
        Party_acccode = Common.accCodeValue;
        Party_acctypename = Common.accTypeName;
        Party_accname = Common.accCodeName;

        txtAccCodeName.Text = Common.accCodeName;
        txtAccTypeName.Text = Common.accTypeName;

        txtAccTypeValue.Text = Common.accTypeValue.ToString();
        txtAccCodeValue.Text = Common.accCodeValue.ToString();

        Button_Delivery.Enabled = true;
        Button_PutItem.Enabled = true;

    }
    protected void Button_Delivery_Click(object sender, EventArgs e)
    {

        try
        {
            if (string.IsNullOrEmpty(TextBox_DeliveryCharge.Text)) {Label1.Text="error 914: empty charge"; return;}
            if (!(Common.IsRightDecimalEntry(TextBox_DeliveryCharge.Text)))
            {
                Label1.Text = "Error: 914 Not a right decimal";
                return;
            }
            
            
            
            DataTable dtCreditAccBuffer = new DataTable();
            DataTable dtDebitAccBuffer = new DataTable();
            dtCreditAccBuffer = (DataTable)Session["Account Credit Entry"];
            dtDebitAccBuffer = (DataTable)Session["Account Debit Entry"];


            decimal dcharge = Convert.ToDecimal(TextBox_DeliveryCharge.Text);
            dtCreditAccBuffer.Rows.Add("01/01/2001", "", 0, 3, 83, "Other Income", "Delivery Charges Received", dcharge, "To " + Party_accname);
            dtDebitAccBuffer.Rows.Add("01/01/2001", "", 0, Party_acccode, Party_acctype, Party_acctypename, Party_accname, dcharge,"Delivery Charge");

            GridView1.DataSource = null;
            GridView1.DataSource = dtDebitAccBuffer;
            GridView1.DataBind();
        

            GridView2.DataSource = null;
            GridView2.DataSource = dtCreditAccBuffer;
            GridView2.DataBind();


            if (Session["Account Credit Entry"] != null)
            {
                Session.Remove("Account Credit Entry");
            }
            Session.Add("Account Credit Entry", dtCreditAccBuffer);

            if (Session["Account Debit Entry"] != null)
            {
                Session.Remove("Account Debit Entry");
            }
            Session.Add("Account Debit Entry", dtDebitAccBuffer);

            Button_Delivery.Enabled=false;
        }
        catch (Exception Ex)
        {

            Label1.Text = Ex.Message;
            throw;
        }
    }
    protected void Button_Summary_Click(object sender, EventArgs e)
    {
        DataTable dtCreditAccBuffer = new DataTable();
        DataTable dtDebitAccBuffer = new DataTable();
        dtCreditAccBuffer = (DataTable)Session["Account Credit Entry"];
        dtDebitAccBuffer = (DataTable)Session["Account Debit Entry"];
        int no_of_credit_accounts = dtCreditAccBuffer.Rows.Count;
        int no_of_Debit_accounts = dtDebitAccBuffer.Rows.Count;

        decimal total_debit = 0;
        foreach (DataRow accrow in dtCreditAccBuffer.Rows)
        {
            total_debit = total_debit + Convert.ToDecimal(accrow["amount"]);
        }
        decimal total_credit = 0;
        foreach (DataRow accrow in dtDebitAccBuffer.Rows)
        {
            total_credit = total_credit + Convert.ToDecimal(accrow["amount"]);
        }
            
        DataTable dtMemoBuffer = new DataTable();
        dtMemoBuffer = (DataTable)Session["Finished Good Entry"];

        DataTable dtBriefMemoBuffer = dtMemoBuffer.Clone();

        string filterExp = "ton > 0 or pcs > 0";
        DataRow[] drarray;
        drarray = dtMemoBuffer.Select(filterExp);

        foreach (DataRow row in drarray)
        {
            dtBriefMemoBuffer.ImportRow(row);
        }
        int no_of_items = dtBriefMemoBuffer.Rows.Count;
    

        decimal total_cost_of_items = 0;
        decimal total_ton = 0;
        foreach (DataRow row in dtBriefMemoBuffer.Rows)
        {
            //row["rowtotal"] = Convert.ToDecimal(row["ton"]) * Convert.ToDecimal(row["cost"]) + Convert.ToDecimal(row["pcs"]) * Convert.ToDecimal(row["cost"]);
            total_cost_of_items = total_cost_of_items + Convert.ToDecimal(row["rowtotal"]);
            total_ton = total_ton + Convert.ToDecimal(row["ton"]);
        }
        TextBox_totalcredit.Text = total_credit.ToString();
        TextBox_totaldebit.Text = total_debit.ToString();
        TextBox_itemtotal.Text = total_cost_of_items.ToString() + " Taka, " + total_ton.ToString() + " Ton"; ;

    }

    private void GetDateCookie()
    {
        try
        {
            HttpCookie myCookie = Request.Cookies[DATE_INFO];
            if (myCookie == null)
            {
                //No cookie found or cookie expired.
                //Handle the situation here, Redirect the user or simply return;
                //TO DO here
                //lblCookieMessage.Visible = true;
                //lblCookieMessage.Text = "no Cookie found!";

                return;
            }
            if (!string.IsNullOrEmpty(myCookie.Values[DATE_INFO]))
            {
                string strDate = myCookie.Values[DATE_INFO].ToString();
                TextBoxDate.Text = strDate;
                //Yes userId is found. Mission accomplished.
            }
        }
        catch (Exception)
        {

            throw;
        }
    }
}
